package com.atguigu.gmall.realtime.app;


import com.atguigu.gmall.realtime.util.FlinkSourceUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2022/4/14 14:22
 */
public abstract class BaseAppV2 {
    public abstract void handle(StreamExecutionEnvironment env,
                                Map<String, DataStreamSource<String>> stream);
    
    public void init(String jobName, int port, int p, String ck, String groupId, String firstTopic,
                     String... otherTopics) {
        System.setProperty("HADOOP_USER_NAME", "atguigu");
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", port);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(p);
        
        env.enableCheckpointing(3000);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop162:8020/gmall/" + ck);
        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
        
        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.DELETE_ON_CANCELLATION);
        
        ArrayList<String> topics = new ArrayList<>();
        topics.add(firstTopic);
        topics.addAll(Arrays.asList(otherTopics));
    
        Map<String, DataStreamSource<String>> topicAndStreamMap = new HashMap<>();
        for (String topic : topics) {
            
            DataStreamSource<String> stream = env.addSource(FlinkSourceUtil.getKafkaSource(groupId, topic));
            topicAndStreamMap.put(topic, stream);
        }
        
        
        //具体的业务怎么?
        handle(env, topicAndStreamMap);
        
        
        try {
            env.execute(jobName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}
